package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.ThroadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;
    @Override
    public Result follow(Long id, Boolean isFollow) {

        Long userId = ThroadLocal.get().getId();
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(id);
        String key = RedisConstants.FOLLOW_KEY+userId;
         if(isFollow){

            boolean isSuccess =  save(follow);


                 stringRedisTemplate.opsForSet().add(key,id.toString());

         }
         else{

             followMapper.Delete(follow);
             stringRedisTemplate.opsForSet().remove(key,id.toString());
         }
         return Result.ok();
    }

    @Override
    public Result isFollow(Long id) {
        Long userId = ThroadLocal.get().getId();
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(id);
        if(followMapper.Select(follow) != null){
            return Result.ok(true);
        }
        else{
            return Result.ok(false);
        }
    }

    @Override
    public Result followcommon(Long id) {
        Long userId = ThroadLocal.get().getId();
        String key1 = RedisConstants.FOLLOW_KEY+userId;
        String key2= RedisConstants.FOLLOW_KEY+id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1,key2);
        if(intersect == null|| intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> users = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }
}
